package me.jiatao.kotlinmall.mvp.presenter

import io.reactivex.Observable
import io.reactivex.functions.BiFunction
import me.jiatao.baselibrary.mvp.presenter.BasePresenter
import me.jiatao.baselibrary.rx.BaseSubscriber
import me.jiatao.baselibrary.rx.execute
import me.jiatao.kotlinmall.data.protocol.Article
import me.jiatao.kotlinmall.data.protocol.ArticleResponseBody
import me.jiatao.kotlinmall.data.protocol.Banner
import me.jiatao.kotlinmall.mvp.service.impl.HomeServiceImpl
import me.jiatao.kotlinmall.mvp.view.HomeView
import javax.inject.Inject

class HomePresenter @Inject constructor() : BasePresenter<HomeView>() {

    @Inject
    lateinit var homeService: HomeServiceImpl

    /**
     * 获取轮播图
     */
    private fun requestBanner() {
        homeService.getBanners()
            .execute(object : BaseSubscriber<List<Banner>>(mView) {
                override fun onNext(data: List<Banner>) {
                    mView.setBanner(data)
                }
            }, mLifecycleProvider)
    }

    /**
     * 获取文章数据
     */
    fun requestArticles(num: Int) {
        homeService.getArticles(num)
            .execute(object : BaseSubscriber<ArticleResponseBody>(mView) {
                override fun onNext(data: ArticleResponseBody) {
                    mView.setArticles(data)
                }

            }, mLifecycleProvider)
    }

    /**
     * 刷新首页全部数据
     */
    fun requestHomeData() {
        requestBanner()

        Observable.zip(homeService.getTopArticles(), homeService.getArticles(0),
            BiFunction<
                    MutableList<Article>,
                    ArticleResponseBody,
                    ArticleResponseBody>
            { t1, t2 ->
                t1.forEach {
                    // 置顶数据中没有标识，手动添加一个标识
                    it.top = "1"
                }
                t2.datas.addAll(0, t1)
                t2
            }
        ).execute(object : BaseSubscriber<ArticleResponseBody>(mView) {
            override fun onNext(data: ArticleResponseBody) {
                mView.setArticles(data)
            }

        }, mLifecycleProvider)
    }

}